package svgToPng;


import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;

import java.io.*;

public class SvgToPngConverter {

    public static void convertSvgToPng(String svgFilePath, String pngFilePath, int width, int height) throws IOException, TranscoderException {
        // 创建PNG转码器
        JPEGTranscoder t = new JPEGTranscoder();
        //设置背景色为黑色
        //t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, new java.awt.Color(0, 0, 0));

        //指定压缩质量为最高质量
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, 1.0f);
        // 设置输出图像的宽度和高度
        t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) width);
        t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) height);
        File file = new File(svgFilePath);
        InputStream inputStream = new FileInputStream(file);
        // 准备输入和输出
        TranscoderInput input = new TranscoderInput(inputStream);
        FileOutputStream ostream = new FileOutputStream(pngFilePath);
        TranscoderOutput output = new TranscoderOutput(ostream);

        // 执行转换
        t.transcode(input, output);

        // 关闭输出流
        ostream.close();
    }

    public static void main(String[] args) {
        try {
            String svgFilePath = "C:\\Users\\瑾瑜\\Desktop\\sql\\20230621\\diagram (2).svg";
            String pngFilePath = "C:\\Users\\瑾瑜\\Desktop\\sql\\20230621\\diagram (2).jpg";
            int width = 7680; // 指定宽度
            int height = 4320; // 指定高度
            convertSvgToPng(svgFilePath, pngFilePath, width, height);
            System.out.println("SVG转换为PNG成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

